<template>
  <div>
    <page-header-wrapper content="用户管理用于对用户进行增删改查">
    </page-header-wrapper>
    <div style="height: 30px"></div>
    <!-- table -->
    <a-card>
      <a-table
        :columns="columns"
        :dataSource="data"
        :pagination="false"
        :loading="memberLoading"
      >
        <!--编辑时弹出来的框-->
        <template v-for="(col, i) in ['username', 'roleId']" :slot="col" slot-scope="text, record">
            <a-input
              :key="col"
              v-if="record.editable && col==='username'"
              style="margin: -5px 0"
              :value="text"
              :placeholder="columns[i].title"
              @change="e => handleChange(e.target.value, record.key, col)"
            />
          <a-select
            :key="col"
            v-if="record.editable && col==='roleId'"
            v-bind:default-value=roleList[0].roleName
            style="width: 120px"
            @change="e => selectHandleChange(e, record.key, col)"
          >
            <a-select-option
              v-for="role in roleList"
              :key="role.id"
            >
              {{ role.roleName }}
            </a-select-option>
          </a-select>
          <template v-if="!record.editable">{{ text }}</template>
        </template>
        <!--消息体-->
        <template slot="operation" slot-scope="text, record">
          <template v-if="record.editable">
            <span v-if="record.isNew">
              <a @click="saveRow(record)">添加</a>
              <a-divider type="vertical" />
              <a-popconfirm title="是否要删除此行？" @confirm="remove2(record.id)">
                <a style="color: red">删除</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a @click="saveRow2(record)">保存</a>
              <a-divider type="vertical" />
              <a @click="cancel(record.id)">取消</a>
            </span>
          </template>
          <span v-else>
            <a @click="toggle(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm title="是否要删除此行？" @confirm="remove(record)">
              <a style="color: red">删除</a>
            </a-popconfirm>
          </span>
        </template>
      </a-table>
      <a-button style="width: 100%; margin-top: 16px; margin-bottom: 8px" type="dashed" icon="plus" @click="newMember">新增成员</a-button>
    </a-card>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { PageHeaderWrapper } from '@ant-design-vue/pro-layout'
import TagSelectOption from '@/components/TagSelect/TagSelectOption'
export default {
  name: 'Authority',
  components: {
    PageHeaderWrapper,
    TagSelectOption
  },
  data () {
    return {
      loading: false,
      memberLoading: false,
      data: [],
      originalData: [],
      columns: [
        {
          title: '用户名',
          dataIndex: 'username',
          key: 'username',
          editable: false,
          scopedSlots: { customRender: 'username' }
        },
        {
          title: '角色',
          dataIndex: 'roleId',
          key: 'roleId',
          editable: false,
          scopedSlots: { customRender: 'roleId' }
        },
        {
          title: '操作',
          key: 'action',
          editable: false,
          scopedSlots: { customRender: 'operation' }
        }
      ],
      temp: [],
      roleList: [],
      defaultRoleId: '',
      yuansishuju: []
    }
  },
  methods: {
    // 跨组件穿透 在index.js中注册，vuex
    ...mapActions(['FindAllUser', 'DeleteById', 'GetRoleAll', 'AddUser', 'UpdateByUserId']),
    show () {
      const {
        FindAllUser
      } = this
      FindAllUser().then(res => {
        // 原始数据用来在更新或插入时对比用户名是否重复  所以更新和插入成功后务必要刷新它
        this.originalData = JSON.parse(JSON.stringify(res))
        // 插入字段
        this.insertEditable(res)
        // 字段插入完毕后赋值给 data
        this.data = this.temp
        console.log(this.data)
      })
    },
    getRoleAll () {
      const {
        GetRoleAll
      } = this
      GetRoleAll().then(res => {
        this.roleList = res.result
        this.defaultRoleId = this.roleList[0].id
      })
    },
    insertEditable (data) {
      // 编辑时需要editable字段的值做判断，所以将每个json对象塞进去一个editable和key字段
      this.temp = []
      for (let i = 0; i < data.length; i++) {
        // 原因在于在Vue实例创建时， obj.b 并未声明，因此就没有被Vue转换为响应式的属性，自然就不会触发视图的更新，这时就需要使用Vue的全局api—— $set()：
        this.$set(data[i], 'editable', false)
        this.$set(data[i], 'key', i)
        // 以下是错误示例
        // data[i].editable = false
        // data[i].key = i
        this.temp.push(data[i])
      }
    },
    newMember () {
      const length = this.data.length
      this.data.push({
        key: length === 0 ? '1' : (parseInt(this.data[length - 1].key) + 1).toString(),
        username: '',
        roleId: '',
        editable: true,
        isNew: true
      })
    },
    handleChange (value, key, column) {
      const newData = [...this.data]
      const target = newData.find(item => key === item.key)
      if (target) {
        target[column] = value
        target['roleId'] = this.defaultRoleId
        this.data = newData
      }
    },
    selectHandleChange (value, key, column) {
      const newData = [...this.data]
      const target = newData.find(item => key === item.key)
      if (target) {
        target[column] = value
        this.defaultRoleId = value
        this.data = newData
      }
    },
    saveRow2 (record) {
      this.memberLoading = true
      const { username, roleId } = record
      if (!username || !roleId) {
        this.memberLoading = false
        this.$message.error('请填写完整成员信息。')
        return
      }
      for (let i = 0; i < this.originalData.length; i++) {
        if (username === this.originalData[i].username) {
          this.memberLoading = false
          this.$message.error('用户名已存在')
          return
        }
      }
      for (let i = 0; i < this.roleList.length; i++) {
        if (record.roleId === this.roleList[i].roleId) {
            record.roleId = this.roleList[i].id
            return
        } else {
          record.roleId = this.defaultRoleId
        }
      }
      const { UpdateByUserId } = this
      UpdateByUserId(record).then((res) => {
        const target = this.data.find(item => item.id === record.id)
        if (res.code === '200') {
          target.editable = false
          target.username = record.username
          target.roleId = this.findRoleName(target.roleId)
          this.memberLoading = false
          // 刷新原始数据
          this.originalData = JSON.parse(JSON.stringify(this.data))
        } else {
          this.$message.error(res.message)
          target.editable = false
          this.memberLoading = false
        }
      })
    },
    findRoleName (id) {
      let roleName = ''
      for (let i = 0; i < this.roleList.length; i++) {
        if (id === this.roleList[i].id) {
          roleName = this.roleList[i].roleName
          return roleName
        } else {
          roleName = '没有设定角色'
        }
      }
      return roleName
    },
    saveRow (record) {
      this.memberLoading = true
      const { key, username, roleId } = record
      if (!username || !roleId) {
        this.memberLoading = false
        this.$message.error('请填写完整成员信息。')
        return
      }
      for (let i = 0; i < this.originalData.length; i++) {
        if (username === this.originalData[i].username) {
          this.memberLoading = false
          this.$message.error('用户名已存在')
          return
        }
      }
      // 模拟网络请求、卡顿 800ms
      // new Promise((resolve) => {
      //   setTimeout(() => {
      //     resolve({ loop: false })
      //   }, 800)
      // }).then(() => {
      //   const target = this.data.find(item => item.key === key)
      //   target.editable = false
      //   target.isNew = false
      //   this.memberLoading = false
      // })
      const {
        AddUser
      } = this
      AddUser(record).then((res) => {
        console.log(res)
        if (res.code === '200') {
          const target = this.data.find(item => item.key === key)
          for (let i = 0; i < this.roleList.length; i++) {
              if (target.roleId === this.roleList[i].id) {
                  target.roleId = this.roleList[i].roleName
              }
          }
          target.id = res.result.id
          target.editable = false
          target.isNew = false
          // 关闭加载状态
          this.memberLoading = false
          // 刷新原始数据
          this.originalData = JSON.parse(JSON.stringify(this.data))
        } else {
          this.$message(res.message)
          // 关闭加载状态
          this.memberLoading = false
        }
      })
    },
    remove (key) {
      console.log(key)
      const {
        DeleteById
      } = this
      DeleteById(key).then((res) => {
        if (res.code === '200') {
          this.show()
        } else {
          this.$message(res.message)
        }
      })
    },
    remove2 (key) {
      const newData = this.data.filter(item => item.id !== key)
      this.data = newData
    },
    cancel (key) {
      const target = this.data.find(item => item.id === key)
      Object.keys(target).forEach(key => { target[key] = target._originalData[key] })
      target._originalData = undefined
    },
    toggle (key) {
      const target = this.data.find(item => item.key === key.key)
      target._originalData = { ...target }
      target.editable = !target.editable
    }
  },
  created () {
    // 获取所有用户信息
    this.show()
    // 获取角色
    this.getRoleAll()
  }
}
</script>

<style lang="less">
@import '~ant-design-vue/lib/style/themes/default.less';
</style>
